package com.android.bonn.fast.drawable.tags;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

import androidx.annotation.NonNull;

/**
 * author huangyunlin@snqu.com
 * date 2018/12/6
 * description
 */
public class BackGroundSpan extends ImageSpan {

    private int expandWidth = 0; //设置之后可能会出现显示不全的问题，可通过TextView的 padding解决
    private int expandHeight = 0;//设置之后可能会出现显示不全的问题，可通过TextView的 padding解决

    public BackGroundSpan(@NonNull Drawable drawable, int expandWidth, int expandHeight) {
        super(drawable, ALIGN_BASELINE);
        this.expandWidth = expandWidth;
        this.expandHeight = expandHeight;
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        super.draw(canvas, text, start, end, x, top, y, bottom, paint);
        int width = getWidth(text, start, end, paint);
        int height = getHeight(paint);
        //getDrawable().setBounds(0, 0, width, height);
        //float bgX = x - (expandWidth * 0.5F); //使得在水平方向居中
        //int bgBottom = bottom + expandHeight / 2;//使得在垂直方向居中
        //canvas.drawText(text.subSequence(start, end).toString(), x, y, paint);
    }


    /**
     * 计算span的宽度
     *
     * @param text
     * @param start
     * @param end
     * @param paint
     * @return
     */
    private int getWidth(CharSequence text, int start, int end, Paint paint) {
        return Math.round(paint.measureText(text, start, end)) + expandWidth;
    }

    /**
     * 计算span的高度
     *
     * @param paint
     * @return
     */
    private int getHeight(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.ascent) + expandHeight;
    }


}
